package com.lf.service.impl;

import com.lf.dao.TokenDao;
import com.lf.dao.UserDao;
import com.lf.pojo.LagouToken;
import com.lf.pojo.User;
import com.lf.service.AuthCodeService;
import com.lf.service.UserService;
import com.lf.util.CookieUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Reference(check = false)
    private AuthCodeService authCodeService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private TokenDao tokenDao;

    @Override
    public boolean register(String email, String password, String code) {

        // 检查 该 email 是否已经注册过
        if(isRegistered(email)) {
            return false;
        }
        // 检查 code 是否有效
        if(authCodeService.checkEmailAndCode(email,code) != 0) {
            return false;
        }

        // 执行注册逻辑，构造 user 对象保存到数据库
        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        userDao.save(user);
        return true;
    }

    @Override
    public boolean isRegistered(String email) {
        User user = userDao.findOneByEmail(email);
        if(user == null) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public boolean login(String email, String password, HttpServletResponse response) {
        User user = userDao.findOneByEmail(email);
        // 检查用户是否存在
        if(user == null) {
            return false;
        }

        // 检查用户名密码是否正确
        if(!user.getPassword().equals(password)) {
            return false;
        }


        // 检查是否已经存在 token
        LagouToken lagouToken = tokenDao.findOneByEmail(email);
        if(lagouToken == null) {
            // 使用 uuid 模拟 token 生成保存在数据库中
            UUID uuid = UUID.randomUUID();
            lagouToken = new LagouToken();
            lagouToken.setEmail(email);
            lagouToken.setToken(uuid.toString());
            lagouToken = tokenDao.save(lagouToken);
        }
        // 将 token 设置到浏览器 cookie中
        CookieUtil.setCookie(response,"token",lagouToken.getToken(),100000);
        return true;
    }

    @Override
    public String getEmailByToken(String token) {
        String email = "";
        LagouToken lagouToken = tokenDao.findOneByToken(token);
        if(lagouToken != null) {
            email = lagouToken.getEmail();
        }
        return email;
    }
}
